from nicegui import ui
import re
from src.utils.loggers import chaxunfenxi_logger
import time

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from src.app import APP


class Content_ChaxunFenxi:

    class Data_Storage:
        '''
            保存当前页面的数据
        '''
        coord_data = None
        chaxuncedian_list = []
        chaxun_fangxiang = 'X'
        chaxun_vin_lasts = []  # 存储选中的checkbox值
        columnVinDict = {}
        custom_count = 0  # 自定义数量

    def __init__(self, container, app: 'APP') -> None:
        self.container = container
        self.APP: 'APP' = app

    def chaxunfenxi(self):
        """创建仪表盘内容"""
        with self.container:
            self.container_01 = ui.column().classes('full-width q-gutter-md')
            self.chaxunfenxi_01_01_cedianxuanze()
            self.chaxunfenxi_01_02()
            self.chaxunfenxi_01_03()

    def chaxunfenxi_01_01_cedianxuanze(self):
        with self.container_01:
            with ui.card().classes('full-width q-gutter-md col'), ui.column().classes('full-width'):
                ui.label('测点选择').classes('text-h6')
                with ui.row().classes('full-width'):
                    self.chaxunfenxi_01_01_cedianxuanze_input = ui.input(label='测点号', placeholder="KN0001L, kN0002R").props("outlined ").classes(
                        'col-grow').style('flex: 5')

                    ui.button('解析测点号', on_click=self.shurucedian_jiexi).classes(
                        'col-grow').style('flex: 2')

                    self.chaxunfenxi_01_01_cedianxuanze_label = ui.label('解析结果').classes(
                        'col-grow text-h6 text-center').style('flex: 5')

    def shurucedian_jiexi(self):
        """解析测点号"""
        shurucedian = self.chaxunfenxi_01_01_cedianxuanze_input.value
        if not shurucedian:
            shurucedian = 'KN0001L, KN0002R'

        shurucedian_Upper = shurucedian.upper()  # 转换为大写以匹配

        # 正则表达式匹配 AB1234C 格式
        pattern = r'[A-Z]{2}\d{4}[A-Z]'

        # 查找所有匹配的字符串
        matches = re.findall(pattern, shurucedian_Upper)

        if matches:
            # 显示匹配结果
            result = f"找到 {len(matches)} 个匹配: {', '.join(matches)}"
            ui.notify(result)

            # 更新解析结果显示
            # 这里可以添加代码来更新界面上的标签或其他元素
            # 例如：self.update_result_display(matches)
            self.chaxunfenxi_01_01_cedianxuanze_label.text = result
            self.Data_Storage.chaxuncedian_list = matches

            chaxunfenxi_logger.info(f"解析测点号 {shurucedian} 成功，匹配到 {matches}")
        else:
            ui.notify("未找到符合格式的测点号")

        return matches

    def chaxunfenxi_01_02(self):
        with self.container_01:
            with ui.card().classes('col full-width q-gutter-md'):
                ui.label('VIN选择').classes('text-h6')

                with ui.card_section().classes('full-width'):
                    with ui.column():
                        # 选择 X 或 Y 或 Z 三个方向的radio，选项横向排列
                        self.chaxunfenxi_01_02_fangxinag = ui.radio(
                            ['X', 'Y', 'Z'], value='X').classes('flex flex-row gap-4').style('flex: 5')
                        self.chaxunfenxi_01_02_fangxinag.bind_value(
                            self.Data_Storage, 'chaxun_fangxiang')

                        # ui.label('选择方向').bind_text_from(
                        # self.Data_Storage, 'chaxun_fangxinag').classes('col-grow').style('flex: 5')

                with ui.card_section().classes('full-width'):
                    self.chaxunfenxi_01_02_vincheckbox_group = {}
                    # FIXME :如果storage还没有值，就运行可能会有问题
                    try:
                        self.Data_Storage.columnVinDict = self.APP.NiceGUIApp.storage.client[
                            'columnVinDict']
                        chaxunfenxi_logger.info(
                            f'columnVinDict 列数 {len(self.Data_Storage.columnVinDict)}')

                        self.Data_Storage.coord_data = self.APP.NiceGUIApp.storage.client[
                            'coord_data']
                        chaxunfenxi_logger.info(
                            self.Data_Storage.coord_data.shape)

                    except:
                        self.Data_Storage.columnVinDict = {}

                    # while len(self.Data_Storage.columnVinDict) == 0:
                    #     time.sleep(0.1)

                    #     self.Data_Storage.columnVinDict = self.APP.NiceGUIApp.storage.client.get(
                    #         'columnVinDict', {})
                    #     chaxunfenxi_logger.info(
                    #         f'columnVinDict 列数 {len(self.Data_Storage.columnVinDict)}')

                    if 1:

                        self.Data_Storage.coord_data = self.APP.NiceGUIApp.storage.client[
                            'coord_data']
                        chaxunfenxi_logger.info(
                            self.Data_Storage.coord_data.shape)

                    with ui.grid(columns=10):
                        for last, vin in self.Data_Storage.columnVinDict.items():
                            # 为每个选项创建checkbox
                            last_vin_6 = vin[-6:] if vin else last
                            self.chaxunfenxi_01_02_vincheckbox_group[last] = ui.checkbox(
                                text=last_vin_6,
                                value=last in self.Data_Storage.chaxun_vin_lasts,  # 初始状态
                                on_change=lambda e, opt=last: self.update_checkbox_group(
                                    e.value, opt)
                            )

                    with ui.row():
                        ui.button('全选', on_click=self.select_all)
                        ui.button('取消', on_click=self.clear_selection)
                        ui.button('反选', on_click=self.reverse_selection)
                        with ui.row():
                            ui.number('自定义数量').bind_value(
                                self.Data_Storage, 'custom_count').on('keydown', lambda e: self.custom_selection() if e.args.get('key') == 'Enter' else None)
                            ui.button('自定义数量', on_click=self.custom_selection)

    def select_all(self):
        """全选所有checkbox"""
        self.Data_Storage.chaxun_vin_lasts = list(
            self.Data_Storage.columnVinDict.keys())
        chaxunfenxi_logger.debug(self.Data_Storage.chaxun_vin_lasts)

        self.refresh_checkbox_group()

    def clear_selection(self):
        """取消所有选择"""
        self.Data_Storage.chaxun_vin_lasts = []
        self.refresh_checkbox_group()

    def reverse_selection(self):
        """反选所有checkbox"""
        all_options = set(self.Data_Storage.columnVinDict.keys())
        selected = set(self.Data_Storage.chaxun_vin_lasts)
        self.Data_Storage.chaxun_vin_lasts = list(all_options - selected)
        self.refresh_checkbox_group()

    def custom_selection(self):
        """根据自定义数量选择checkbox"""
        count = int(self.Data_Storage.custom_count)

        all_options = list(self.Data_Storage.columnVinDict.keys())
        self.Data_Storage.chaxun_vin_lasts = all_options[
            :count]
        self.refresh_checkbox_group()

    def update_checkbox_group(self, is_checked: bool, option: str):
        """同步checkbox状态到列表"""
        if is_checked:
            if option not in self.Data_Storage.chaxun_vin_lasts:
                self.Data_Storage.chaxun_vin_lasts.append(option)
        else:
            if option in self.Data_Storage.chaxun_vin_lasts:
                self.Data_Storage.chaxun_vin_lasts.remove(option)
        # 可选：打印选中状态（用于调试）
        # print(f"当前选中: {self.Data_Storage.selected_checkboxes}")

    def refresh_checkbox_group(self):
        """刷新checkbox组"""
        for last in self.Data_Storage.columnVinDict:
            self.chaxunfenxi_01_02_vincheckbox_group[last].value = last in self.Data_Storage.chaxun_vin_lasts

    def chaxunfenxi_01_03(self):
        def get_chaxun_data():
            if self.Data_Storage.coord_data is None:
                return
            direction = self.Data_Storage.chaxun_fangxiang

            df01 = self.Data_Storage.coord_data[self.Data_Storage.coord_data['方向'] == direction]
            # print(df01)

            print(self.Data_Storage.chaxuncedian_list)
            df02 = df01[df01['特征点号'].isin(self.Data_Storage.chaxuncedian_list)]
            print(df02)

            df02.set_index('特征点号', inplace=True)

            df03 = df02[self.Data_Storage.chaxun_vin_lasts]

            print(df03)

            # 转换为字典格式， index是键，每行数据是一个列表
            result_dict = {idx: row.tolist() for idx, row in df03.iterrows()}

            # 此时是last_xx 格式 列表
            x_data = df03.columns.tolist()
            # 转换为VIN list 列表
            x_data = [self.Data_Storage.columnVinDict[item] for item in x_data]
            # 取最后6位vin
            x_data = [item[-6:] for item in x_data if item]

            # print(x_data)

            # print(result_dict)

            self.trend_chart.options['xAxis']['data'] = x_data

            self.trend_chart.options['series'].clear()
            for item in result_dict:
                self.trend_chart.options['series'].append(
                    {'data': result_dict[item], 'type': 'line', 'name': item})

            self.trend_chart.update()

        with self.container_01:
            with ui.card().classes('col full-width q-gutter-md'):
                ui.button('查看测点趋势', on_click=get_chaxun_data)
                self.trend_chart = ui.echart({
                    'title': {'text': '测点趋势图'},
                    'tooltip': {},
                    'legend': {},
                    'xAxis': {
                        'axisLabel': {
                            'interval': 0,
                            'rotate': 90
                        }
                    },
                    'yAxis': {},
                    'series': []
                }).classes('w-full h-64').style('width: 100%; height: 400px; background: #f5f5f5;')
